package com.hzz.framework.filter;

import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

@Slf4j
public class RewriteFilter implements Filter {

    /**
     * 需要rewrite到的目的地址
     */
    public static final String REWRITE_TO = "rewriteUrl";

    /**
     * 拦截的url,url通配符之前用英文分号隔开
     */
    public static final String REWRITE_PATTERNS = "rewritePatterns";

    private Set<String> urlPatterns = null;//配置url通配符

    private String rewriteTo = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        rewriteTo = filterConfig.getInitParameter(REWRITE_TO);
        String exceptUrlString = filterConfig.getInitParameter(REWRITE_PATTERNS);
        if (StringUtil.isEmpty(exceptUrlString)) {
            urlPatterns = Collections.emptySet();
        } else {
            urlPatterns = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(exceptUrlString.split(";", 0))));
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String servletPath = httpServletRequest.getServletPath();
        String context = httpServletRequest.getContextPath();
        if (isMatches(urlPatterns, servletPath)) {
            log.info("=======================isMatches:" + servletPath);
            request.getRequestDispatcher(context + "/" + rewriteTo).forward(httpServletRequest, response);
        } else if (servletPath.contains("main")) {//兼容处理main和main#
            log.info("========================main:" + servletPath);
            request.getRequestDispatcher(context + "/" + rewriteTo).forward(httpServletRequest, response);
        } else {
            log.info("=======================other:" + servletPath);
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void destroy() {
    }

    private boolean isMatches(Set<String> patterns, String url) {
        if (null == patterns) {
            return false;
        }
        for (String str : patterns) {
            if (str.endsWith("/*")) {
                String name = str.substring(0, str.length() - 1);
                if (url.contains(name)) {
                    return true;
                }
            } else {
                Pattern pattern = Pattern.compile(str);
                if (pattern.matcher(url).matches()) {
                    return true;
                }
            }
        }
        return false;
    }
}